package com.zxl.grocery.core.webmagic.scheduled;


import com.zxl.grocery.common.persistence.model.CrawlerConfig;
import com.zxl.grocery.core.webmagic.pipeline.BeautifulPipeline;
import com.zxl.grocery.core.webmagic.processor.WallProcessor;
import com.zxl.grocery.modular.crawler.service.ICrawlerConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Spider;

import java.util.HashMap;
import java.util.List;

/**
 * info:美图定时任务
 * Created by Lzx on 2017/7/12.
 */
@Component
public class BeautifulScheduled {

    @Autowired
    private BeautifulPipeline beautifulPipeline;
    @Autowired
    private ICrawlerConfigService iCrawlerConfigService;

    /**
     * 3G壁纸站
     */
    ////[秒] [分] [小时] [日] [月] [周] [年]
    @Scheduled(cron = "0 0 0/4 * * ? ")//从0点开始,每4个小时执行一次
    public void wallScheduled() {
        HashMap<String,Object> conditionMap = new HashMap<String,Object>();
        conditionMap.put("code","WallScheduled");
        List<CrawlerConfig> crawlerConfigs = iCrawlerConfigService.selectByMap(conditionMap);

        if (crawlerConfigs.size() > 0 ) {
            for (int i = 0; i < crawlerConfigs.size(); i++) {
                if (crawlerConfigs.get(i).getContent().equals("1")){
                    HashMap<String,Object> conMap = new HashMap<String,Object>();
                    conMap.put("code","WallScheduledNum");
                    List<CrawlerConfig> crawlerConfigList = iCrawlerConfigService.selectByMap(conMap);
                    if (crawlerConfigList.size() > 0) {
                        for (int j = 0; j < crawlerConfigList.size(); j++) {
                            if(StringUtils.isNotEmpty(crawlerConfigList.get(j).getContent())){
                                System.out.println("----开始执行3G壁纸站定时任务");
                                Spider spider= Spider.create(new WallProcessor());
                                int num=Integer.valueOf(crawlerConfigList.get(j).getContent())+1;
                                System.out.println(crawlerConfigList.get(j).getContent());
                                spider.addUrl("http://www.3gbizhi.com/lists-%E5%85%A8%E9%83%A8/"+num+".html");
                                spider.addPipeline(beautifulPipeline);
                                spider.thread(5);
                                spider.setExitWhenComplete(true);
                                spider.start();
                                spider.stop();
                                crawlerConfigList.get(j).setContent(num+"");
                                iCrawlerConfigService.insertOrUpdate(crawlerConfigList.get(j));
                            }
                        }

                    }
                }

            }

        }

    }
}
